package com.qianli.cashmama.trade.controller;

import com.alibaba.fastjson.JSON;
import com.fqgj.common.api.Response;
import com.fqgj.common.api.annotations.ParamsValidate;
import com.fqgj.common.utils.TimeUtils;
import com.fqgj.xjd.user.client.response.User;
import com.qianli.cashmama.pay.client.domain.query.response.FundAccountInfoResponse;
import com.qianli.cashmama.trade.client.trade.TradeApplicationService;
import com.qianli.cashmama.trade.client.trade.request.PayResultRequest;
import com.qianli.cashmama.trade.controller.request.ArtificialCallbackRequest;
import com.qianli.cashmama.trade.domain.model.BizRecord;
import com.qianli.cashmama.trade.domain.model.TradeBase;
import com.qianli.cashmama.trade.integration.notification.message.MessageIntegrationService;
import com.qianli.cashmama.trade.integration.pay.PayIntegrationService;
import com.qianli.cashmama.trade.integration.user.UserIntegrationService;
import com.qianli.cashmama.trade.integration.user.dto.UserBankDto;
import com.qianli.cashmama.trade.repo.BizRecordRepository;
import com.qianli.cashmama.trade.repo.TradeBaseRepository;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * @author zsp
 * @date 2020-03-29
 */
@RestController
@RequestMapping("/payment/notify")
public class PaymentCallbackController {
    private static final Logger LOGGER = LoggerFactory.getLogger(PaymentCallbackController.class);

    @Autowired
    private TradeApplicationService tradeApplicationService;

    @Autowired
    private BizRecordRepository bizRecordRepository;

    @Autowired
    private TradeBaseRepository tradeBaseRepository;

    @Autowired
    private MessageIntegrationService messageIntegrationService;

    @Autowired
    private UserIntegrationService userIntegrationService;

    @Autowired
    private PayIntegrationService payIntegrationService;

    /**
     * 支付放款回调
     *
     * @param request
     * @return
     */
    @ParamsValidate
    @RequestMapping("/pay")
    public Response paymentCallback(@RequestBody ArtificialCallbackRequest request) {
        LOGGER.info("放款回调请求参数,request:{}", JSON.toJSONString(request));
        try {
            request.validate();
            String bizNo = request.getBizNo();
            boolean isSuccess = "0000".equals(request.getCode());
            String fundSiteCode = request.getFundSiteCode();

            BizRecord bizRecord = bizRecordRepository.load(bizNo);
            String tradeNo = bizRecord.getInnerNo();
            TradeBase tradeBase = tradeBaseRepository.load(tradeNo);
            if (tradeBase == null) {
                LOGGER.warn("订单号不存在,{}", tradeNo);
                return Response.ok().putData(null);
            }
            String userCode = tradeBase.getUserCode();

            PayResultRequest payResultRequest = new PayResultRequest()
                    .setResultCode(request.getCode())
                    .setPayBizNo(request.getAcceptNo())
                    .setPaySuccess(isSuccess)
                    .setTradeNo(bizNo)
                    .setResultMsg(request.getMessage())
                    .setReceivedDate(TimeUtils.getDateByStr(request.getTripleAcceptDate(), "yyyy-MM-dd HH:mm:ss"))
                    .setPayRetry(request.isAllowedToRetry());

            if (StringUtils.isNotEmpty(fundSiteCode) || !Objects.equals("null", fundSiteCode)) {
                try {
                    payResultRequest.setCapitalCode(Integer.valueOf(fundSiteCode));
                } catch (NumberFormatException e) {
                    LOGGER.error("转换异常", e);
                }
            }
            UserBankDto userBankDto = null;
            try {
                //卡信息要提早查
                userBankDto = userIntegrationService.getUserBankSnapshotByUserCode(userCode);
            } catch (Exception e) {
            }

            LOGGER.info("放款通知交易请求交易参数,params:{}", JSON.toJSONString(payResultRequest));
            Response response = tradeApplicationService.payCallBackV2(payResultRequest);
            LOGGER.info("放款通知交易,交易结果,response:{}", JSON.toJSONString(response));

            if (userBankDto != null) {
                //发短信+邮件
                User user = userIntegrationService.getUserByUserCode(userCode);
                String nbfcName = "NBFC";
                try {
                    FundAccountInfoResponse fundAccountInfoResponse = payIntegrationService.getNbfcByFundCode(payResultRequest.getCapitalCode());
                    if (fundAccountInfoResponse != null && StringUtils.isNotEmpty(fundAccountInfoResponse.getNbfcCompanyName())) {
                        nbfcName = fundAccountInfoResponse.getNbfcCompanyName();
                    }
                } catch (Exception e) {
                    LOGGER.warn("获取nbfc信息失败,capitalCode", payResultRequest.getCapitalCode());
                }
                String amount = tradeBase.getBorrowTotalCapital().setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString();
                if (isSuccess) {
                    messageIntegrationService.loanSuccessNote(userCode, tradeNo, user.getMobile(), userBankDto.getCardNo(), user.getName(), nbfcName, amount);
                } else if (payResultRequest.getPayRetry()) {
                    messageIntegrationService.loanFailAndRebindNote(userCode, tradeNo, user.getMobile(), userBankDto.getCardNo(), user.getName());
                }
            }

            return Response.ok();
        } catch (Exception e) {
            LOGGER.error("放款回调处理异常,bizNo:" + request.getBizNo(), e);
            return Response.error();
        }
    }

}
